import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        cartList: []
    },
    mutations: {
        // 加一
        addCounter(state,payload){
            payload.count++
        },
        // 加入数组
        addToCart(state,payload){
            payload.count = 1
            payload.checked=false
            state.cartList.push(payload)
        }
    },
    actions: {
        addCart(context, payload) {
            return new Promise((resolve,reject)=>{
                // 查找之前数组中是否有该商品
                let oldProduct = context.state.cartList.find(item => item.iid === payload.iid)
                // 判断oldProduct
                if (oldProduct) {
                    // oldProduct.count += 1
                    context.commit('addCounter',oldProduct)
                    resolve('添加到购物车+1')
                } else {
                    // payload.count = 1
                    // context.state.cartList.push(payload)
                    context.commit('addToCart',payload)
                    resolve('添加成功！')
                }
            })
        }
    },
    getters:{
        cartLength(state){
            return state.cartList.length
        },
        cartList(state){
            return state.cartList
        }
    },
    modules: {
    }
})
